package com.github.hgkmail.hello.config;

import com.github.hgkmail.hello.plugins.CatMybatisInterceptor;
import com.github.hgkmail.hello.plugins.CatMybatisPlugin;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration //注册到springboot 容器中
@MapperScan(basePackages = "com.github.hgkmail.hello.dao.ry",  //通过分包来配置多数据源
        sqlSessionTemplateRef  = "rySqlSessionTemplate")
public class RyDSConfig {

    @Value("${spring.datasource.ry.jdbc-url}")
    private String jdbcUrl;

    @Bean(name = "ryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.ry")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "rySqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory
            (@Qualifier("ryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //添加CAT插件
//        CatMybatisPlugin.addCatMybatisPlugin(bean);
//        CatMybatisInterceptor.addCatMybatisInterceptor(bean, jdbcUrl);
        return bean.getObject();
    }

    @Bean(name = "ryTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager
            (@Qualifier("ryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "rySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate
            (@Qualifier("rySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
